/* sha256.c
**
** Copyright (c) 2007, Meadhbh S. Hamrick
** All rights reserved.
** 
** Redistribution  and  use  in  source  and  binary  forms,  with  or  without
** modification, are permitted provided that the following conditions are met:
** 
**  * Redistributions of  source code must  retain the above  copyright notice,
**    this list of conditions and the following disclaimer.
** 
**  * Redistributions in binary form must reproduce the above copyright notice,
**    this list of conditions and the following disclaimer in the documentation
**    and/or other materials provided with the distribution.
** 
**  * Neither the  name of  Project Meadhbh  nor the names of  its contributors
**    may be used  to endorse  or promote  products derived from this  software
**    without specific prior written permission.
** 
** THIS SOFTWARE IS PROVIDED BY  THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
** AND ANY  EXPRESS OR IMPLIED WARRANTIES,  INCLUDING, BUT NOT  LIMITED TO, THE
** IMPLIED WARRANTIES  OF MERCHANTABILITY AND FITNESS FOR  A PARTICULAR PURPOSE
** ARE DISCLAIMED.  IN NO  EVENT SHALL THE  COPYRIGHT OWNER OR  CONTRIBUTORS BE
** LIABLE  FOR  ANY  DIRECT,   INDIRECT,  INCIDENTAL,  SPECIAL,  EXEMPLARY,  OR
** CONSEQUENTIAL  DAMAGES  (INCLUDING,  BUT  NOT  LIMITED  TO,  PROCUREMENT  OF
** SUBSTITUTE GOODS  OR SERVICES;  LOSS OF USE,  DATA, OR PROFITS;  OR BUSINESS
** INTERRUPTION)  HOWEVER CAUSED  AND ON  ANY THEORY  OF LIABILITY,  WHETHER IN
** CONTRACT,  STRICT LIABILITY,  OR  TORT (INCLUDING  NEGLIGENCE OR  OTHERWISE)
** ARISING IN ANY WAY  OUT OF THE USE OF THIS SOFTWARE,  EVEN IF ADVISED OF THE
** POSSIBILITY OF SUCH DAMAGE.
** 
** $Id: sha256.c 48 2007-08-30 21:49:44Z msh.mobile $
*/

/** \file sha256.c
 ** This file implements the SHA256 cryptographic hash function.
 */

/* Macro Definitions */

#ifndef MC_ROTATE_LEFT
#define MC_ROTATE_LEFT(x,n,b) (((x)<<(n))|((x)>>(b-n)))
#endif

#ifndef MC_ROTATE_RIGHT
#define MC_ROTATE_RIGHT(x,n,b) (((x)>>(n))|((x)<<(b-n)))
#endif

#ifndef MC_SHIFT_RIGHT
#define MC_SHIFT_RIGHT(x,n) ((x)>>(n))
#endif

#define MC_MIC_SHA256_CH(x,y,z) ( ( ( x ) & ( y ) )^ ( (~(x) ) & ( z ) ) )
#define MC_MIC_SHA256_MA(x,y,z) ( ( ( x ) & ( y ) ) ^ ( ( x ) & ( z ) ) ^ ( ( y ) & ( z ) ) )
#define MC_MIC_SHA256_BS0(x) ((MC_ROTATE_RIGHT((x),2,32))^(MC_ROTATE_RIGHT((x),13,32))^(MC_ROTATE_RIGHT((x),22,32)))
#define MC_MIC_SHA256_BS1(x) ((MC_ROTATE_RIGHT((x),6,32))^(MC_ROTATE_RIGHT((x),11,32))^(MC_ROTATE_RIGHT((x),25,32)))
#define MC_MIC_SHA256_LS0(x) ((MC_ROTATE_RIGHT((x),7,32))^(MC_ROTATE_RIGHT((x),18,32))^(MC_SHIFT_RIGHT(x,3)))
#define MC_MIC_SHA256_LS1(x) ((MC_ROTATE_RIGHT((x),17,32))^(MC_ROTATE_RIGHT((x),19,32))^(MC_SHIFT_RIGHT(x,10)))


/* File Includes */
#include "mutil.h"
#include "mcrypto/sha256.h"

/* Static Prototypes */

static void mc_mic_sha256_transform( tMCSha256 *context );

/* Static Variables */

static uint32_t mc_mic_sha256_constants[64] = {
  0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
  0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 
  0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
  0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 
  0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
  0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 
  0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
  0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, 
  0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
  0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 
  0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
  0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 
  0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
  0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 
  0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
  0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 
};

void mc_mic_sha256_clone( tMCSha256 *new_context, tMCSha256 *old_context ) {
  memcpy( new_context, old_context, sizeof( tMCSha256 ) );
}

/** \fn tMCErr mc_mic_sha256_clear( tMCSha256 *context )
**  \brief clear sensitive data from the context
*/
void mc_mic_sha256_clear( tMCSha256 *context ) {
  mc_mic_sha256_initialize( context );
}

/** \fn tMCErr mc_mic_sha256_initialize( tMCSha256 *context )
**  \brief initialize a SHA256 context to it's initial condition
*/
void mc_mic_sha256_initialize( tMCSha256 *context ) {
  context->count = 0;

  memset( context->data.asChar, 0, 256 );

  context->state[0] = 0x6A09E667;
  context->state[1] = 0xBB67AE85;
  context->state[2] = 0x3C6EF372;
  context->state[3] = 0xA54FF53A;
  context->state[4] = 0x510E527F;
  context->state[5] = 0x9B05688C;
  context->state[6] = 0x1F83D9AB;
  context->state[7] = 0x5BE0CD19;
}
 
/** \fn tMCErr mc_mic_sha256_update( tMCSha256 *context, uint8_t *data, uint32_t length )
**  \brief provide input to the hash function
*/

void mc_mic_sha256_update( tMCSha256 *context, uint8_t *data, uint32_t length ) {
  uint32_t input_index;
  uint32_t block_index;

  for( input_index = 0; input_index < length; input_index ++ ) {

    /* copy data into the buffer */
    block_index = context->count % 64;
    context->data.asChar[ block_index ] = data[ input_index ];

    /* update the counter */
    context->count++;

    /* if the block buffer is full, transform the data */
    if( 63 == block_index ) {
      mc_mic_sha256_transform( context );
    }
  }
}

/** \fn tMCErr mc_mic_sha256_digest( tMCSha256 *context, uint8_t *digest )
**  \brief get the digest of the data provided
*/
void mc_mic_sha256_digest( tMCSha256 *context, uint8_t *digest ) {
  uint32_t next_pad_index;
  uint32_t i;

  /* where does the first padding byte go? */
  next_pad_index = ( context->count % 64 );

  /* put the first padding byte */
  context->data.asChar[ next_pad_index++ ] = 0x80;

  /* are we past the 56th byte in the data buffer? */

  if( next_pad_index > 55 ) {
    mc_mic_sha256_transform( context );
    next_pad_index = 0;
  }

  for( ; next_pad_index < 56; next_pad_index++ ) {
    context->data.asChar[ next_pad_index ] = 0;
  }

  /* append count to block */

  /* todo: find a platform independent way of doing a hton on long longs */
  context->data.asLongLong[ 7 ] = MU_HTON64(context->count * 8);

  /* call transform */

  mc_mic_sha256_transform( context );

  /* we may have to change state endianness */

#ifndef WORDS_BIGENDIAN
  for( i=0; i<8; i++ ) {
    context->state[i] = MU_HTON32( context->state[i] );
  }
#endif

  /* copy state to digest */
  memcpy( digest, (uint8_t *) context->state, 32 );
}

/** \fn void mc_mic_sha256_transform( tMCSha256 *context )
**  \brief "churn" the internal state of the SHA256 context based on input data
*/
static void mc_mic_sha256_transform( tMCSha256 *context ) {
  uint32_t local_state[8];
  uint32_t t1, t2;
  uint32_t i;

  /* depending on the endianness of the processor, we may have to change */
  /* the endianness of the data array                                    */

#ifndef WORDS_BIGENDIAN
  for( i = 0; i < 16; i++ ) {
    context->data.asInt[i] = ( uint32_t ) MU_HTON32( context->data.asInt[i] );
  }
#endif

  /* Prepare the Message Schedule */
  /* note: the update and digest calls already place the first 16 words of
  ** the message in the data member.
  */
  for( i=16; i<64; i++ ) {
    context->data.asInt[ i ] = (uint32_t) (
      MC_MIC_SHA256_LS1( context->data.asInt[ i - 2 ] ) +
      context->data.asInt[ i - 7 ] +
      MC_MIC_SHA256_LS0( context->data.asInt[ i - 15] ) +
      context->data.asInt[ i - 16] );
  }

  /* Initialize Working Variables */

  local_state[ 0 ] = context->state[ 0 ];
  local_state[ 1 ] = context->state[ 1 ];
  local_state[ 2 ] = context->state[ 2 ];
  local_state[ 3 ] = context->state[ 3 ];
  local_state[ 4 ] = context->state[ 4 ];
  local_state[ 5 ] = context->state[ 5 ];
  local_state[ 6 ] = context->state[ 6 ];
  local_state[ 7 ] = context->state[ 7 ];

  for( i = 0; i < 64; i++ ) {
    t1 = (uint32_t) (
      local_state[7] + MC_MIC_SHA256_BS1( local_state[4] ) +
      MC_MIC_SHA256_CH( local_state[4], local_state[5], local_state[6] ) +
      mc_mic_sha256_constants[ i ] +
      context->data.asInt[ i ] );
    t2 = (uint32_t) (
      MC_MIC_SHA256_BS0( local_state[0] ) +
      MC_MIC_SHA256_MA( local_state[0], local_state[1], local_state[2] ) );
    local_state[7] = local_state[6];
    local_state[6] = local_state[5];
    local_state[5] = local_state[4];
    local_state[4] = local_state[3] + t1;
    local_state[3] = local_state[2];
    local_state[2] = local_state[1];
    local_state[1] = local_state[0];
    local_state[0] = t1 + t2;
  }

  /* add the local_state back into the context state */
  context->state[ 0 ] += local_state[ 0 ];
  context->state[ 1 ] += local_state[ 1 ];
  context->state[ 2 ] += local_state[ 2 ];
  context->state[ 3 ] += local_state[ 3 ];
  context->state[ 4 ] += local_state[ 4 ];
  context->state[ 5 ] += local_state[ 5 ];
  context->state[ 6 ] += local_state[ 6 ];
  context->state[ 7 ] += local_state[ 7 ];

  memset( context->data.asChar, 0, 256);
}
